import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { addOhPackageDps, commonFileOperation, commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibrary]: 1,
  },
};

/**
 *  1. entry模块添加library，entry依赖该library
 *  2. 在library模块级hvigorfile.ts动态修改library的版本号
 *  3. 构建har包，并检查是否library版本号被改动
 *  3. 构建hap包
 *  4. 检查语境信息表中library的版本号是否被改动
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();

  // 修改工程 build-profile.json5 的 strictMode 信息，否则构建产物中没有语境信息表
  await commonJson5Operation(path.resolve(projectRoot, 'build-profile.json5'), async (json5) => {
    json5.app.products[0].buildOption = {
      strictMode: {
        useNormalizedOHMUrl: true,
      },
    };
  });

  /**
   *     1. 增加entry模块对library模块的依赖
   *     2. 需要在src/main/ets/pages/Index.ets里面加入import以及MainPage()
   */
  const entryPath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryPath, { staticLibrary: 'file:../staticLibrary' });

  await commonFileOperation(path.join(entryPath, 'src', 'main', 'ets', 'pages', 'Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return `import { MainPage } from 'staticLibrary';\nMainPage();\n${content}`;
  });

  /**
   * 1. 增加library模块中的export function
   * 2. 修改library模块中hvigorfile.ts插件
   */
  const libraryPath = project.getModule('staticLibrary').moduleRootPath();
  // 修改模块级library 的 version 信息为1.1.1
  await commonJson5Operation(path.resolve(libraryPath, 'oh-package.json5'), async (json5) => {
    json5.version = '1.1.1';
  });

  const apiCode = `import { harTasks, OhosHarContext,OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
export function customPlugin(options: OnlineSignOptions): HvigorPlugin {
    return {
        pluginId: 'customPlugin',
        context() {
            return {
                signConfig: options };},
        async apply(currentNode: HvigorNode): Promise<void> {
            const harContext = currentNode.getContext(OhosPluginId.OHOS_HAR_PLUGIN) as OhosHarContext;
            harContext?.targets((target: Target) => {
                const targetName = target.getTargetName();
                if (targetName === 'default') {
                    let version = harContext.getVersion();
                    version= '2.0.0';
                    harContext.setVersion(version);}
            })
            ;} };}
export default {
    system: harTasks,
    plugins:[customPlugin()]
}`;

  fse.writeFileSync(path.resolve(libraryPath, 'hvigorfile.ts'), apiCode, 'utf-8');

  // 构建 release har 包
  const assembleHapCmd = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
  });

  const assembleHapResult = await runHvigorAsync(projectRoot, assembleHapCmd);
  record.addStep('编译entry,依赖library', assembleHapResult);
  expect(assembleHapResult.stdout).toContain('BUILD SUCCESSFUL');
  expect(fse.existsSync(path.resolve(entryPath, 'build', 'default', 'intermediates', 'loader', 'default', 'pkgContextInfo.json'))).toEqual(true);

  /**
   * 构建成功，解析hap包，查看语境信息表中的信息和dependencyMap中的信息,应该符合经过hvigorfile修改的信息
   */
  const pkgContextInfoPath = path.resolve(entryPath, 'build', 'default', 'intermediates', 'loader', 'default', 'pkgContextInfo.json');
  const text = fse.readFileSync(pkgContextInfoPath).toString();
  const jsonData = JSON.parse(text);
  const libraryVersion = jsonData.staticLibrary?.version;
  expect(libraryVersion).toEqual('2.0.0');
};

TestCaseBuilder.builder()
  .caseName('DTS2024110425283')
  // eslint-disable-next-line max-len
  .description('DTS未收集被依赖模块动态修改的版本号')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();
